import { reactive } from 'vue'
import { PaginationDefault } from '../constant'

export interface Pagination {
  pageSize: number
  pageSizes: number[]
  total: number
  layout?: string
  pageChange: (page: number) => void
  pageSizeChange: (size: number) => void
  currentPage?: number
}

export interface Operation<T> {
  onDataOperation: (index: number, row: T) => void
  icon?: string
  permissionCode?: string
}

export interface PureTable<T> {
  data: T[]
  rowKey?: string // 树状table需要
  refreshTableData: () => void
  initTableData: () => void
}

export interface OperationTable<T> extends PureTable<T> {
  onTableDataEdit: (index: number, row: T) => void
  editPermissionCode?: string
  onTableDataDelete: (index: number, row: T) => void
  deletePermissionCode?: string
  extraOperations?: Operation<T>[]
}

export interface PagTable<T> extends OperationTable<T> {
  pagination: Pagination
}

export class DefaultPureTable<T> implements PureTable<T> {
  constructor(config?: Partial<PureTable<T>>) {
    Object.assign(this, config)
  }
  data: T[] = reactive([])
  refreshTableData = () => {}
  initTableData = () => {
    this.refreshTableData()
  }
}

export class DefaultOperationTable<T> extends DefaultPureTable<T> implements OperationTable<T> {
  constructor(config?: Partial<OperationTable<T>>) {
    super(config)
    Object.assign(this, config)
  }
  onTableDataEdit = (index: number, row: T) => {}
  onTableDataDelete = (index: number, row: T) => {}
}

export class DefaultPagTable<T> extends DefaultOperationTable<T> implements PagTable<T> {
  constructor(config?: Partial<PagTable<T>>) {
    super(config)
    Object.assign(this, config)
  }
  data: T[] = reactive([])
  pagination: Pagination = reactive({
    pageSize: PaginationDefault.pageSize,
    pageSizes: PaginationDefault.pageSizes,
    total: 0, // 初始值设为 0
    layout: PaginationDefault.layout,
    currentPage: 1,
    pageChange: () => {
      this.refreshTableData()
    },
    pageSizeChange: () => {
      this.pagination.currentPage = 1 // 重置当前页为第一页
      this.refreshTableData() // 这里不会再进入pageChange回调
    },
  })
  initTableData = () => {
    if (this.pagination) {
      this.pagination.currentPage = 1 // 重置当前页为第一页
    }
    this.refreshTableData()
  }
  onTableDataEdit = (index: number, row: T) => {}
  onTableDataDelete = (index: number, row: T) => {}
}
